import json
import tablib
import smtplib
import datetime
import pytz
import time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.utils import formataddr
from email.mime.application import MIMEApplication


# 获取json数据
with open('baseline-autotest.json', 'r', encoding="UTF-8") as f:
    rows = json.load(f)

# 将json中的key作为header, 也可以自定义header（列名）
header = tuple([i for i in rows[0].keys()])

data = []
# 循环里面的字典，将value作为数据写入进去
for row in rows:
    body = []
    for v in row.values():
        body.append(v)
    data.append(tuple(body))

data = tablib.Dataset(*data, headers=header)
pytz_ = datetime.datetime.fromtimestamp(int(time.time()), pytz.timezone('Asia/Shanghai')).strftime('%Y-%m-%d %H:%M:%S')
subject_xls = '%s测试报告.xls' % (pytz_.split(' ')[0])
open(subject_xls, 'wb').write(data.xls)


# 你的邮箱所使用的邮件服务器
mail_host = "smtp.qq.com"
# 你的邮箱
mail_user = "2019772541@qq.com"
# 你的邮箱密码
mail_pass = "cbgnunfvaqbwdifi"

# 接收邮箱列表
recv = 'wll1913789144@163.com'

m = MIMEMultipart()
m['From'] = formataddr(("wangliliang", mail_user))
m['to'] = formataddr(("wll", recv))


pytz_ = datetime.datetime.fromtimestamp(int(time.time()), pytz.timezone('Asia/Shanghai')).strftime('%Y-%m-%d %H:%M:%S')

# 标题
subject = '%s 测试报告' % (pytz_.split(' ')[0])
m['Subject'] = Header(subject, 'utf-8')

# 文字描述内容
m.attach(MIMEText('这是测试报告文件', 'plain', 'utf-8'))

# 添加xls文件
att1 = MIMEApplication(open(subject_xls, 'rb').read())
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写，写什么名字，邮件中显示什么名字
# att1.add_header('Content-Disposition', 'attachment', filename=('utf8', '', '%s-%s-%s 激活.xlsx'.encode('utf-8') % (str(datetime.date.today().year), datetime.date.today().month, datetime.date.today().day)))
att1.add_header('Content-Disposition', 'attachment', filename=('%s-%s-%s 测试报告.xlsx' % (str(datetime.date.today().year), datetime.date.today().month, datetime.date.today().day)))
m.attach(att1)

try:
    smtpObj = smtplib.SMTP()
    smtpObj.connect(mail_host, 25)
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(mail_user, recv, m.as_string())
    print("发送邮件成功！！！")
    # 退出
    smtpObj.quit()
except smtplib.SMTPException:
    print("发送邮件失败！！！")
